package com.bsoft.service.impl;

import com.bsoft.Exception.CommonException;
import com.bsoft.aop.annotation.MultiDataSourceTransactional;
import com.bsoft.mapper.business.EcgMapper;
import com.bsoft.mapper.lis.HivPushMapper;
import com.bsoft.service.EcgService;
import com.bsoft.utils.ConmonUtil;
import net.sf.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.EnableTransactionManagement;
import org.springframework.util.Assert;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.util.*;

@Service
@EnableTransactionManagement
public class EcgServiceImpl  extends ConmonUtil implements EcgService {
    private static Logger logger = LoggerFactory.getLogger(EcgServiceImpl.class);

    @Resource
    private EcgMapper ecgMapper;

    // 你可以根据需要更改输出目录
    private static final String OUTPUT_DIR = "D:/pdfImage/";

    static {
        // 确保输出目录存在
        File dir = new File(OUTPUT_DIR);
        if (!dir.exists()) {
            dir.mkdirs();
        }
    }

    /**
     * 2.2 获取病人信息接口
     */
    @Override
    public String getPatientInfo(String applyId) throws Exception {
        Assert.notNull(applyId,"申请单号[applyId]不能为空!");
        Map<String,Object>  patientInfoMap = ecgMapper.getPatientInfo(applyId);
        if (ObjectUtils.isEmpty(patientInfoMap)) throw new CommonException("未找到患者申请单[applyId:"+applyId+"]信息!");

        JSONObject res = new JSONObject();

        res.put("code",0);
        res.put("msg","ok");
        res.put("patientInfo",patientInfoMap);
        return res.toString();
    }

    /**
     * 2.5 回传诊断报告接口(HIS)
     */
    @Override
    @MultiDataSourceTransactional(transactionManagers = {"hisTransactionManager", "portalTransactionManager"})
    public String publishResult(Map<String, Object> req) throws Exception {

        isNUll(req, Arrays.asList("applyId","reportDoctor","reportTime","type","data"));

        String url ="";
        byte[] decodedBytes=null;
        if ("1".equals(req.get("type").toString())){
            url = req.get("data").toString();
        }else if ("0".equals(req.get("type").toString())){
            decodedBytes = Base64.getDecoder().decode(req.get("data").toString());
        }else {
            throw  new CommonException("目前HIS只支持Url类型[type=0]报告回传!");
        }

        //获取申请单的信息
        Map<String,Object> sqdInfoMap =  ecgMapper.getJcsqInfo(req);
        if (ObjectUtils.isEmpty(sqdInfoMap)) throw  new CommonException("未找到HIS[EMR_JCSQ]申请单[applyId:SQDH:"+req.get("applyId")+"]开单信息!");


        //获取报告主建
        Long JLXH = getIdentity("emr", "EMR_JCBG");
        Map<String, Object> jcbg = new HashMap<>();
        jcbg.put("JLXH", JLXH);// 记录序号 NUMERIC(18) 18
        jcbg.put("JZLX", sqdInfoMap.get("JZLX"));// 就诊类型 NUMERIC(2) 2    就诊类型1：门诊 2：住院
        jcbg.put("JZXH", sqdInfoMap.get("JZHM"));// 就诊序号 NUMERIC(18) 18    门诊：就诊序号（YS_MZ_JZLS.JZXH）住院：住院号（ZY_BRRY.ZYH）
        jcbg.put("JZHM", sqdInfoMap.get("JZHM"));// 就诊号码 VARCHAR(18) 18    和JZXH冗余，避免Oracle中因强类型转换而浪费数据库资源
        jcbg.put("BRBH", sqdInfoMap.get("BRID"));// 病人编号 VARCHAR(32) 32    门诊：门诊号码（MS_BRDA.MZHM）住院：住院号码（ZY_BRRY.ZYHM）
        jcbg.put("SQDH", req.get("applyId"));// 申请单号 NUMERIC(18) 18 是   申请单唯一号
        // jcbg.put("KDRQ",KDRQ);// 开单日期 DATETIME  是
        jcbg.put("KDKS", sqdInfoMap.get("KDKS"));// 开单科室 VARCHAR(50) 50 是   科室名称
        jcbg.put("KDYS", sqdInfoMap.get("KDYS"));// 开单医生 VARCHAR(10) 10 是   医生姓名
        jcbg.put("KDRQ", sqdInfoMap.get("KDSJ"));// 开单时间
        jcbg.put("JCLX", sqdInfoMap.get("JCLX"));// 检查类型 VARCHAR(50) 50    如:B超，CT
        jcbg.put("JCJG", req.get("JCJG")+"");// 检查结果 VARCHAR(4000) 4000
        jcbg.put("LCZD", req.get("LCZD"));// 临床诊断 VARCHAR(255) 255
        jcbg.put("YXZT", "");// 阳性状态 VARCHAR(20) 20 是
        jcbg.put("BGKS", "");// 报告科室 VARCHAR(50) 50 是
        jcbg.put("BGYS", req.get("reportDoctor"));// 报告医生 VARCHAR(20) 20 是
        jcbg.put("BGRQ", req.get("reportTime"));// 报告日期 DATETIME  是

        // 将字节数组转换为字符串，假设原始数据是 UTF-8 编码的文本
//        String decodedString = new String(decodedBytes, StandardCharsets.UTF_8);
        jcbg.put("JCBG", decodedBytes);

        jcbg.put("REP_URL", url);
        jcbg.put("ReportId", "");
        jcbg.put("IMG_URL", url);
//        platforInterfaceMapper.delectJcbg(jcbg); //存在一个申请单多份报告
        List<Map<String, Object>> bgList = ecgMapper.getJcbg(req.get("applyId").toString());
        if (bgList.size()==1){
            //更新报告
            ecgMapper.upJcbg(jcbg);
        }else if (bgList.size()>1){
            throw new CommonException("HIS库已存在相同的多份报告(EMR_JCBG.reportId="+req.get("applyId")+"),请核实!");
        }else {
            ecgMapper.saveJcbg(jcbg);
        }


        JSONObject res = new JSONObject();
        res.put("code",0);
        res.put("msg","ok");
        return res.toString();
    }



    @Override
    public String uploadImage(Map<String, Object> req) {
        // 从请求中获取 Base64 编码的字符串 加密 解密
        String base64EncryptData = req.get("data").toString();
        // 解码 Base64 字符串为字节数组
        byte[] imageBytes = Base64.getDecoder().decode(base64EncryptData);
        // 将字节数组转换为输入流
        // 读取输入流为 BufferedImage（假设输入是 PNG 格式，你可以根据实际情况调整）
        // 将字节数组转换为输入流并读取为 BufferedImage
        try (InputStream inputStream = new ByteArrayInputStream(imageBytes)) {
            BufferedImage image = ImageIO.read(inputStream);
            if (image == null) {
                throw new CommonException("图片解析失败，可能不是有效的图像格式!");
            }

            // 保存图像到指定目录
            File outputfile = new File(OUTPUT_DIR + "decoded_image.png");
            // 确保输出目录存在
            outputfile.getParentFile().mkdirs();
            ImageIO.write(image, "png", outputfile);

        } catch (Exception e) {
            throw new CommonException("图片处理或保存时发生异常: " + e.getMessage());
        }

        /*// 保存图像到 PDF 文件
        File outputfile = new File(OUTPUT_DIR + "decoded_image.pdf");
        try (PDDocument document = new PDDocument()) {
            PDPage page = new PDPage();
            document.addPage(page);

            PDImageXObject pdImage = PDImageXObject.createFromBufferedImage(document, image);
            try (PDPageContentStream contentStream = new PDPageContentStream(document, page)) {
                contentStream.drawImage(pdImage, 100, 700); // 调整位置和大小
            }

            document.save(outputfile);
        }
*/

        JSONObject res = new JSONObject();
        res.put("code",0);
        res.put("msg","ok");
        return res.toString();
    }


}
